<?php

namespace app\service;

use app\admin\model\xmwms\purchase\Detail;
use app\common\controller\Backend;
use think\facade\Db;

class PurchaseService
{

     //获取数据库的需求列表
     public static function platform_demand($where, $db, $name)
     {

          $redis = Backend::redis();
          //如果缓存存在 就不查询数据库
          if ($redis->exists('demand_' . $name . '_' . $where['platform'])) {
               $redis_arr = $redis->get('demand_' . $name . '_' . $where['platform']);
               $data = json_decode($redis_arr, true);
          } else {
               //设置redis缓存
               $storageLogs = $db->name('storage_xq_log')->group('xq_id')->select()->toArray();
               $xqNums = $db->name('storage_xq_log')->where('status', 0)->group('xq_id')->column('sum(num)', 'xq_id');
               $buys = $db->name('storage_buy')->where('status', 1)->group('xq_id')->column('sum(num)', 'xq_id');
               $yfps = $db->name('storage_xq_log')->where('status', 1)->group('xq_id')->column('sum(num)', 'xq_id');
               $thumb = $db->name('storage_xq')->column('thumb', 'id');
               $money_price = $db->name('storage_xq')->column('money_price', 'id');
               $stock = $db->name('storage_xq')->column('stock', 'id');
               //我需要获取一个数据最早进入数据库的时间
               $sql = "SELECT xq_id, TIMESTAMPDIFF(DAY, created_at, NOW()) AS days_diff FROM storage_xq_log WHERE status = 0 GROUP BY xq_id ORDER BY days_diff ASC";
               $result = $db->query($sql);
               $max_day_list = array_column($result, 'days_diff', 'xq_id');
               foreach ($storageLogs as $k => $value) {
                    $xq_id = $value['xq_id'];
                    $storageLogs[$k]['max_day'] = $max_day_list[$xq_id] ?? 0;
                    $storageLogs[$k]['xq_num'] = $xqNums[$value['xq_id']] ?? 0;
                    $storageLogs[$k]['purchase_num'] = $xqNums[$xq_id] ?? 0;
                    $storageLogs[$k]['buys'] = $buys[$xq_id] ?? 0;
                    $storageLogs[$k]['yfp'] = $yfps[$xq_id] ?? 0;
                    $storageLogs[$k]['thumb'] = $thumb[$xq_id]?? '';
                    $storageLogs[$k]['demand_sku_id'] = $value['id']?? 0;
                    $storageLogs[$k]['price'] = bcdiv($money_price[$xq_id], 100, 2);
                    $storageLogs[$k]['money_price'] = bcdiv($money_price[$value['xq_id']], 100, 2);
                    $storageLogs[$k]['kfp'] = $stock[$xq_id] - $storageLogs[$k]['yfp'];
                    $storageLogs[$k]['status'] = (($storageLogs[$k]['kfp'] + $storageLogs[$k]['buys']) >= $storageLogs[$k]['purchase_num']) ? 1 : 0;
               }

               $data = array_values($storageLogs);
               //复制一层完全一样的数组--适配其他需求列表
               foreach ($data as &$v) {
                    $v['skus'] = [$v];
               }
               $redis->set('demand_' . $name . '_' . $where['platform'], json_encode($data), ['ex' => 86400]);

          }
          //搜索数据
          if (!empty($where['title'])) {
               $search = $where['title'];
               $data = array_filter($data, function ($v) use ($search) {
                    return stripos($v['title'], $search) !== false;
               });
          }
          //排序order: max_day,asc
          if (!empty($where['order'])) {
               //排序arr数组
               $sort = explode(',', $where['order']);
               $sort_field = $sort[0];
               $sort_type = $sort[1];
               $sort_arr = array_column($data, $sort_field);
               array_multisort($sort_arr, $sort_type == 'asc' ? SORT_ASC : SORT_DESC, $data);
          }
          $perPage = $where['limit'] ?? 10; // 每页显示的数量
          $start = ($where['page'] ?? '1' - 1) * $perPage; // 计算开始位置
          $pageData = array_slice($data, $start, $perPage); // 获取当前页的数据
          return ['list' => $pageData, 'total' => count($data)];
     }

     //获取对应数据库
     public static function platform($platform)
     {
          switch ($platform) {
               case '1':
                    $db = Db::connect('mysql1');
                    $name = 'ckm';
                    break;
               case '2':
                    $db = Db::connect('mysql2');
                    $name = 'yl';
                    break;
               case '3':
                    $db = Db::connect('mysql3');
                    break;
               case '4':
                    $db = Db::connect('mysql4');
                    break;
               case '5':
                    $db = Db::connect('mysql5');
                    break;
               case '6':
                    $db = Db::connect('mysql6');
          }
          $name = $name ?? 'ckm';
          return ['name' => $name, 'db' => $db];
     }

     //获取采购中的数据
     public static function platform_purchase($params)
     {
          $res = Detail::where(['platform' => $params['platform'], 'status' => 3])->select()->toArray();
          return $res;
     }

}
